local base = piece "base"
local turret = piece "turret"
local arms = piece "arms"
local canonsbase = piece "canonsbase"
local leftcanon = piece "leftcanon"
local leftbarrel = piece "leftbarrel"
local rightcanon = piece "rightcanon"
local rightbarrel = piece "rightbarrel"
local flare = piece "flare"

local SIG_AIM = 1

local function Open()
        Signal(2)
        SetSignalMask(1)

        Move(turret, y_axis, 10, 100)
	
	Sleep(50)

	Move(canonsbase, z_axis, 3, 50)
	WaitForMove(canonsbase, z_axis)

	Move(leftcanon, z_axis, 6, 50)
	Move(rightcanon, z_axis, 6, 50)

	WaitForMove(leftcanon, z_axis)
	WaitForMove(rightcanon, z_axis)

	Move(leftbarrel, z_axis, 3, 50)
	Move(rightbarrel, z_axis, 3, 50)

        return true
end

local function Close()
        Signal(1)
        SetSignalMask(2)
	
        Move(canonsbase, z_axis, 0, 50)
        Move(leftcanon, z_axis, 0, 50)
        Move(rightcanon, z_axis, 0, 50)
        Move(leftbarrel, z_axis, 0, 50)
        Move(rightbarrel, z_axis, 0, 50)

	Sleep(50)

	Move(turret, y_axis, 0, 50)
        return true
end

function script.Create()
	Hide(flare)
end

function script.AimWeapon1(heading, pitch)
	Signal(SIG_AIM)
	SetSignalMask(SIG_AIM)
	Turn(turret, y_axis, heading, 0.5)
	Turn(arms, x_axis, -pitch, 0.25)
	WaitForTurn(turret, y_axis)
	WaitForTurn(arms, x_axis)
	return true
end

function script.QueryWeapon1() return turret end

function script.AimFromWeapon1() return turret end

function script.FireWeapon1()
	Show(flare)
	Move(leftcanon, z_axis, -2.4)
	Move(rightcanon, z_axis, -2.4)
	Sleep(150)
	Hide(flare)
	Move(leftcanon, z_axis, 0, 3)
	Move(rightcanon, z_axis, 0, 3)
end

function script.Activate ( )
        StartThread( Open )
end

function script.Deactivate ( )
        StartThread( Close )
end
